//获取url参数
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null)
        return unescape(r[2]);
    return null;
}
//时间格式转换为时间戳
function js_strto_time(time) {
    var new_str = time.replace(/:/g, '-');
    new_str = new_str.replace(/ /g, '-');
    new_str = new_str.replace(/\//g, '-');
    var arr = new_str.split("-");
    var datum = new Date(Date.UTC(arr[0], arr[1] - 1, arr[2], arr[3] - 8, arr[4], arr[5]));
    return strtotime = datum.getTime() / 1000;
}
//时间戳数据转换为时间格式
function js_date_time(unixtime) {
    var timestr = new Date(parseInt(unixtime)*1000);
    var year= timestr.getFullYear(); 
    var month= timestr.getMonth()+1; 
    var date= timestr.getDate(); 
    var hour= timestr.getHours(); 
    var minute= timestr.getMinutes(); 
    var second= timestr.getSeconds(); 
    var datetime = year+"/"+month+"/"+date+" "+hour+":"+minute+":"+second; 
    return datetime;
}
//编辑的时候获取数据填充表单
function showData() {
//    overlayer("open");
    $.ajax({
        type: "POST",
        async: false,
        url: "../../action/policy/get.do",
        data: {type: type, messageNo: id, instance: DepotName},
        dataType: "json",
        success: function(souData) {
            //souData = $.parseJSON(souData);
            var policy_desc = souData.Comment;
            $(".policy_desc").val(policy_desc);
            var data = souData.Content;

            var Packet_Type = data.PacketType;
            $(".Packet_Type").val(Packet_Type);
            optionip($("#Packet_Type").val());
            if (Packet_Type == '2') {
                $(".Packet_Subtype").html("");
                for (var i in datas[1].child) {
                    $(".Packet_Subtype").append("<option value='" + datas[1].child[i].name + "'>" + datas[1].child[i].title + "</option");
                }
            } else if (Packet_Type == '3') {
                $(".Packet_Subtype").html("");
                for (var i in datas[2].child) {
                    $(".Packet_Subtype").append("<option value='" + datas[2].child[i].name + "'>" + datas[2].child[i].title + "</option");
                }
            }
            var Packet_Subtype = data.PacketSubtype;
            $(".Packet_Subtype").val(Packet_Subtype);
            var R_StartTime = data.R_StartTime;
            if (R_StartTime != '0') {
                R_StartTime = js_date_time(data.R_StartTime);
            }
            $(".R_StartTime").val(R_StartTime);
            var R_EndTime = data.R_EndTime;
            if (R_EndTime != '0') {
                R_EndTime = js_date_time(data.R_EndTime);
            }
            $(".R_EndTime").val(R_EndTime);
            var R_Freq = data.R_Freq;
            $(".R_Freq").val(R_Freq);

//        var R_DestIPLength = 4;
//        $(".R_DestIPLength").val(R_DestIPLength);

            var R_DestIP = data.R_DestIP.IPv4Address;
            $(".R_DestIP").val(R_DestIP);

            var R_DestPort = data.R_DestPort;
            $(".R_DestPort").val(R_DestPort);
            var R_Method = data.R_Method;
            $(".R_Method").val(R_Method);
            var UserName = data.UserName;
            $(".UserName").val(UserName);
            var Password = data.Password;
            $(".Password").val(Password);
        }
    });


}
//获取表单数据
function generateParameter() {
    var obj = {};
    obj.PacketType = $(".Packet_Type").val();
    obj.PacketSubtype = $(".Packet_Subtype").val();
    obj.R_StartTime = $(".R_StartTime").val();
    if (obj.R_StartTime == '' || obj.R_StartTime == null) {
        obj.R_StartTime = 0;
    } else {
        obj.R_StartTime = js_strto_time($(".R_StartTime").val());
        // obj.R_StartTime = js_strto_time(obj.R_StartTime);
    }
    obj.R_EndTime = $(".R_EndTime").val();
    if (obj.R_EndTime == '' || obj.R_EndTime == null) {
        obj.R_EndTime = 0;
    } else {
        obj.R_EndTime = js_strto_time($(".R_EndTime").val());
        // obj.R_EndTime = js_strto_time(obj.R_EndTime);
    }
    obj.R_Freq = $(".R_Freq").val();
    obj.R_DestIP = {
        IPType: "IPv4",
        IPv4Address: $(".R_DestIP").val()
    };
    obj.R_DestPort = $(".R_DestPort").val();
    obj.R_Method = $(".R_Method").val();
    obj.UserName = $(".UserName").val();
    obj.Password = $(".Password").val();
    obj.MessageSerialNo = "1";
    return obj;
}
//初始化二级联动列表数据
var objs = {name: 'stair', child: {name: 'second', child: {}}};
var datas = [
    {name: '1', title: '类型 I 数据包', child: [
            {name: '0', title: 'Web 类流量统计', child: []},
            {name: '1', title: 'VoIP 类流量统计', child: []},
            {name: '2', title: '通用流量类统计', child: []},
            {name: '3', title: '访问指定应用的用户统计', child: []},
            {name: '4', title: 'Download 类分析功能模块', child: []},
            {name: '128', title: '用户偏好分析', child: []},
            {name: '129', title: '非法路由检测分析', child: []},
            {name: '130', title: '一拖 N 用户行为分析(检测结果）', child: []},
            {name: '131', title: '一拖 N 用户行为分析(关键字段)', child: []},
            {name: '132', title: 'Web 信息推送结果上报', child: []},
            {name: '192', title: '应用层 DDoS 异常流量分析功能模块', child: []},
            {name: '193', title: 'CP/SP 资源服务器分析模块', child: []},
            {name: '194', title: 'P2P 应用流量流向分析模块', child: []},
            {name: '196', title: '流量流向分析结果上报', child: []}
        ]
    },
    {name: '2', title: '类型 II 数据包', child: [
            {name: '0', title: 'HTTP', child: []},
            {name: '1', title: 'RTSP', child: []},
            {name: '2', title: 'VoIP', child: []},
            {name: '3', title: 'FTP', child: []},
            {name: '4', title: 'SMTP', child: []},
            {name: '5', title: 'POP3', child: []},
            {name: '6', title: 'IMAP', child: []},
            {name: '7', title: 'DNS', child: []},
            {name: '8', title: 'P2P', child: []},
            {name: '9', title: 'Game', child: []},
            {name: '10', title: 'IM', child: []}
        ]
    },
    {name: '3', title: '类型 III 数据包', child: [
            {name: '0', title: 'HTTP GET 报文关键字段上报', child: []},
            {name: '1', title: 'WLAN 终端类型上报', child: []}
        ]
    },
    {name: '240', title: '扩展U接口', child: [
            {name: '131', title: '共享检测扩展U接口（关键字段）', child: []}
        ]
    }

];
//添加数据
function save() {
    var form = $(".form-horizontal").validate();
    if (!form.form()) {
        return;
    }
    var comment = $(".policy_desc").val();
    var policy = JSON.stringify(generateParameter());
    console.log(policy)
    $.ajax({
        type: "POST",
        async: false,
        url: "../../action/policy/create.do",
        data: {comment: comment, policy: policy, type: type, instance: DepotName},
        dataType: "json",
        success: function(data) {
            if (data.result == "true") {
                alert("添加成功！");
                previous();
            } else {
                alert("添加失败!")
            }
        }
    });
}
//编辑数据
function edit() {
    var form = $(".form-horizontal").validate();
    if (!form.form()) {
        return;
    }
    var comment = $(".policy_desc").val();
    var policy = JSON.stringify(generateParameter());
    $.ajax({
        type: "POST",
        async: false,
        url: "../../action/policy/update.do",
        data: {messageNo: id, comment: comment, policy: policy, type: type, instance: DepotName},
        dataType: "json",
        success: function(data) {
            if (data.result == "true") {
                alert("编辑成功！");
                previous();
            } else {
                alert("编辑失败!")
            }
        }
    });
}
//根据用户选择填充上报服务器IP地址
function optionip(number) {
    switch (number) {
        case "1":
            //UD
            $.ajax({
                type: "POST",
                async: false,
                url: "../../action/QueryUddevice.do",
                data: {},
                dataType: "json",
                success: function(data) {
                    var ipcont = $("#R_DestIP").parent();
                    $("#R_DestIP").remove();
                    if (data.length < 1) {
                        ipcont.append("<input type='text' class='R_DestIP ip' id='R_DestIP' name='R_DestIP' required/>");
                        return;
                    }
                    var cont = "<select class='R_DestIP' id='R_DestIP' name='R_DestIP'>"
                    for (var i in data) {
                        cont += "<option value='" + data[i].ip + "'>" + data[i].ip + "</option>"
                    }
                    cont += "</select>"
                    ipcont.append(cont);
                }
            });
            break;
        case "2":
            var ipcont = $("#R_DestIP").parent();
            $("#R_DestIP").remove();
            ipcont.append("<input type='text' class='R_DestIP ip' id='R_DestIP' name='R_DestIP' required/>");
            break;
        case "3":
            //TD
            $.ajax({
                type: "POST",
                async: false,
                url: "../../action/QueryTddevice.do",
                data: {},
                dataType: "json",
                success: function(data) {
                    var ipcont = $("#R_DestIP").parent();
                    $("#R_DestIP").remove();
                    if (data.length < 1) {
                        ipcont.append("<input type='text' class='R_DestIP ip' id='R_DestIP' name='R_DestIP' required/>");
                        return;
                    }
                    var cont = "<select class='R_DestIP' id='R_DestIP' name='R_DestIP'>"
                    for (var i in data) {
                        cont += "<option value='" + data[i].local_ip + "'>" + data[i].local_ip + "</option>"
                    }
                    cont += "</select>"
                    ipcont.append(cont);
                }
            });
            break;
    }
}
//返回上一级
function previous() {
    window.location = "../policyList.html?type=" + type + "&id=" + DepotID + "&name=" + base64.encode(DepotName) + "";
}
/*
 * 查看旧版本的策略内容
 */
function show_oldPolicy(array, number) {
    var souData = array[number];
    $(".header").text("当前策略在" + souData.CreateTime + "创建,ID为" + souData.MessageNo + ",版本号为" + souData.MessageSerialNo + ",属于" + souData.Instance + "策略库");
    
    var policy_desc = souData.Comment;
    $(".policy_desc").val(policy_desc);
    var data = souData.Content;

    var Packet_Type = data.PacketType;
    $(".Packet_Type").val(Packet_Type);
    optionip($("#Packet_Type").val());
    if (Packet_Type == '2') {
        $(".Packet_Subtype").html("");
        for (var i in datas[1].child) {
            $(".Packet_Subtype").append("<option value='" + datas[1].child[i].name + "'>" + datas[1].child[i].title + "</option");
        }
    } else if (Packet_Type == '3') {
        $(".Packet_Subtype").html("");
        for (var i in datas[2].child) {
            $(".Packet_Subtype").append("<option value='" + datas[2].child[i].name + "'>" + datas[2].child[i].title + "</option");
        }
    }
    var Packet_Subtype = data.PacketSubtype;
    $(".Packet_Subtype").val(Packet_Subtype);
    var R_StartTime = data.R_StartTime;
    if (R_StartTime != '0') {
        R_StartTime = js_date_time(data.R_StartTime);
    }
    $(".R_StartTime").val(R_StartTime);
    var R_EndTime = data.R_EndTime;
    if (R_EndTime != '0') {
        R_EndTime = js_date_time(data.R_EndTime);
    }
    $(".R_EndTime").val(R_EndTime);
    var R_Freq = data.R_Freq;
    $(".R_Freq").val(R_Freq);
    var R_DestIP = data.R_DestIP.IPv4Address;
    $(".R_DestIP").val(R_DestIP);

    var R_DestPort = data.R_DestPort;
    $(".R_DestPort").val(R_DestPort);
    var R_Method = data.R_Method;
    $(".R_Method").val(R_Method);
    var UserName = data.UserName;
    $(".UserName").val(UserName);
    var Password = data.Password;
    $(".Password").val(Password);
}

/*
 *获取所有版本的策略内容 
 */
function getAllPolicy() {
    $.ajax({
        type: "GET",
        async: false,
        url: "../../action/policy/history_policy_info.do",
        data: {type: type, instance: getQueryString("DepotName"), messageNo: id},
        dataType: "json",
        success: function(data) {
            policyArray = data;
            policyAmount = data.length
        }
    });
}